    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;
	var layout
	var newLines;
	var count =0;
	var saveType;
    Event.onDOMReady(function() {
		//The configuration of the whole layout of the page
        layout = new YAHOO.widget.Layout({
            units: [
                { position: 'top', height: 100, body: 'top1', gutter: '5px', resize: false },
                { position: 'right', width: 250, header: 'Summary', resize: true, collapse: true, scroll: true, body: 'right1', animate: true },
                { position: 'bottom', height: 30, resize: false, body: 'bottom1', gutter: '5px'},
                { position: 'left', width: 250, header: 'Record', resize: true, body: 'left1', collapse: true, scroll: true, animate: true },
                { position: 'center', body: 'center1', scroll:true }
            ]
        });
		//Sets the home tab of the page
		var myTabs = new YAHOO.widget.TabView("demo");
		myTabs.addTab( new YAHOO.widget.Tab({
			label: 'Home',
			dataSrc: 'home.html',
			cacheData: true,
			active: true
		}), 0);
		
		//Sets the whole Layout at the start of the reloading
        layout.render();
		layout.getUnitByPosition('left').toggle(); 
		layout.getUnitByPosition('right').toggle(); 
		
		//Register Listeners
		Event.addListener('newrec', 'click', newRecord);
		Event.addListener('hide', 'click', hidePanel);
		Event.addListener('editrec', 'click', editRecord);
		Event.addListener('deleterec', 'click', deleteRecord);
		Event.addListener('changeuser', 'click', logOut);
		Event.addListener('submitRecord', 'click', submitRecord);		
		Event.addListener('fromText', 'click', getFromText);
		Event.addListener('fromFile', 'click', getFromFile);
		Event.addListener('search', 'click', search);
		Event.addListener('loginbutton', 'click', logIn);
		Event.addListener('save', 'click', save); //NEW CODE
		Event.addListener('sendrecid', 'click', formIdRequest); //NEW CODE
		Event.addListener('resultPage', 'click', function (){layout.getUnitByPosition('right').toggle();} );
		
		//Checks if a user is already in the cookie. If Yes it automatically logins the user
		if(YAHOO.util.Cookie.get("user")){
			var user = YAHOO.util.Cookie.get("user");
			var acc = YAHOO.util.Cookie.get("acc");
			document.getElementById('userlogged').innerHTML = "Logged in as " + user +":";
			document.getElementById("changeuser").innerHTML = "Log out";
			var tab2 = document.getElementById('recmanagement');
			if(acc == "admin" || acc == "member"){
				if (Dom.getStyle(tab2, 'display') == 'none') {
					Dom.setStyle(tab2, 'display', '');				//Record Management
					var linebreak2 = document.getElementById('linebreak2');
					linebreak2.innerHTML = '<hr/><br/>'
				}
			}
			message("Logged in as "+root.childNodes[0].childNodes[0].nodeValue);
		}
		else{
			document.getElementById('userlogged').innerHTML = "Logged in as guest:";
		}
		
        YAHOO.widget.Logger.enableBrowserConsole();
		
		
    });

	/**
	*Displays the Request form for the ID in the Record Management	
	*/
function toggleRequestId(){
	var selectid = document.getElementById('foredit');
	if(Dom.getStyle(selectid,'display')=='none'){
			return true;
	}
	return false;
}

/**
	* Hide Panel: Toggles the hidden panel that contains the record form
	* 
	*/
function hidePanel() {
	document.getElementById('manage').innerHTML = "";
    var panel = document.getElementById('record');
	var button = document.getElementById('hide');	
    if (Dom.getStyle(panel, 'display') != 'none') {		
        var anim = new YAHOO.util.Anim(panel, { height: { to: 0 } }, .5);
        anim.onComplete.subscribe(function () { Dom.setStyle(panel, 'display', 'none'); Dom.setStyle(button, 'display', 'none'); if(toggleRequestId() == false){
			Dom.setStyle(document.getElementById('foredit'), 'display', 'none'); Dom.setStyle(document.getElementById('sendrecid'), 'display', 'none');
		};});	
        anim.animate();		
    }
	
	
}

/**
*	New Record : Adds a new record to database
*/
function newRecord(){
	var params = "command=id&id=0";
	var callback = {
		success: getNextId,
		failure: requestFailed
	};
	YAHOO.util.Connect.asyncRequest('POST', 'modify', callback, params);
}

/**
*	Retrieves the highest ID +1 in the database. Sets it as the next ID of the new Record
*	Retrieves first the highest before displaying the form. Error Catch
*/

function getNextId(request){
	var xml = request.responseXML;
	if (!xml) {
        error(request.responseText);
		alert("error");
        return;
    }
	var root = xml.documentElement;
	count = root.childNodes[0].nodeValue;
	document.getElementById('manage').innerHTML = "<b>New Record</b>";
	document.getElementById('save').innerHTML = "Add";
	var panel = document.getElementById('record');	
	var button = document.getElementById('hide');	
    if (Dom.getStyle(panel, 'display') == 'none') {
        Dom.setStyle(panel, 'height', '0px');
        Dom.setStyle(panel, 'display', '');
		Dom.setStyle(button, 'display', '');
        var anim = new YAHOO.util.Anim(panel, { height: { to: 1200 } }, .5);
        anim.animate();				
    }
	if(toggleRequestId() == false){
			Dom.setStyle(document.getElementById('foredit'), 'display', 'none');	
	}	
			
	Dom.setStyle(document.getElementById('sendrecid'), 'display', 'none');
	saveType="new";
}

	/**
	*	Edit Record
	*/

function editRecord(){
	document.getElementById('manage').innerHTML = "<b>Edit Record</b>";
	document.getElementById('save').innerHTML = "Save";
	var panel = document.getElementById('record');	
	var button = document.getElementById('hide');
	Dom.setStyle(panel, 'display', 'none');	
    Dom.setStyle(button, 'display', 'none');
	if(toggleRequestId() == true){
			Dom.setStyle(document.getElementById('foredit'), 'display', '');		
	}		
	if( Dom.getStyle(document.getElementById('sendrecid'), 'display') == 'none'){
		Dom.setStyle(document.getElementById('sendrecid'), 'display', '');
	}
	saveType='edit';
}


/**
 *	Delete Record: Deletes a record from database
 */

function deleteRecord(){
	document.getElementById('manage').innerHTML = "<b>Delete Record</b>";
	var panel = document.getElementById('record');	
	var button = document.getElementById('hide');	
	Dom.setStyle(panel, 'display', 'none');
	Dom.setStyle(button, 'display', 'none');
	if(toggleRequestId() == true){
			Dom.setStyle(document.getElementById('foredit'), 'display', '');			
	}
	if( Dom.getStyle(document.getElementById('sendrecid'), 'display') == 'none'){
		Dom.setStyle(document.getElementById('sendrecid'), 'display', '');
	}
	saveType='delete';
}

/**
*  Function for retrievin a record using a Record ID
*/
function formIdRequest(){
	if(saveType == "edit"){
		var params = "id="+document.getElementById('requestid').value;
		var callback = {
			success: getRecordSuccess,
			failure: requestFailed
		};
		YAHOO.util.Connect.asyncRequest('POST', 'modify', callback, params);
	}
	else{
		var params = "command=delete&id=" + document.getElementById('requestid').value;
		var callback = {
			success: deleteSuccess,
			failure: requestFailed
		};
		YAHOO.util.Connect.asyncRequest('POST', 'modify', callback, params);
	}
}

/**
*	Retrieves a record and place it to the form fields
*/

function getRecordSuccess(request){
	var xml = request.responseXML;
	if (!xml) {
        error(request.responseText);
		alert("error");
        return;
    }
	var root = xml.documentElement;
	var panel = document.getElementById('record');	
	var button = document.getElementById('hide');	
    if (Dom.getStyle(panel, 'display') == 'none') {
        Dom.setStyle(panel, 'height', '0px');
        Dom.setStyle(panel, 'display', '');
		Dom.setStyle(button, 'display', '');
        var anim = new YAHOO.util.Anim(panel, { height: { to: 1200 } }, .5);
        anim.animate();				
    }
	for(var x=0;x<root.childNodes.length;x++){
		if(document.getElementById(root.childNodes[x].nodeName+"1")){
			if(root.childNodes[x].childNodes.length !=0){
				document.getElementById(root.childNodes[x].nodeName+"1").value = root.childNodes[x].childNodes[0].nodeValue;
			}
		}
		if(root.childNodes[x].nodeName != "#text"){
			if(root.childNodes[x].childNodes.length !=0){
				if(document.getElementById(root.childNodes[x].childNodes[0].nodeValue+"1")){
					document.getElementById(root.childNodes[x].childNodes[0].nodeValue+"1").click();
				}
			}
		}
	}
}

/**
*	Success in deletion of Record
*/
function deleteSuccess(request){
	message("Record ID:"+document.getElementById('requestid').value+" Deleted");
}

/**
*	Save To File: Saves a record to an XML file and adds it to database.
*/

function save(){	
	var url = 'format/0';
	var callback = {
		success: createData,
		failure: requestFailed
	};
	YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

/**
*	Create Data : Converts form data to XML
*/

function createData(request){	
	var xml = request.responseXML;
	if (!xml) {
        error(request.responseText);
		alert("error");
        return;
    }
	var root = xml.documentElement;
	var params='';
	message("Saving..");
	if(saveType == "edit"){
	params = 'command=edit&id=' + document.getElementById('requestid').value + '&xml=<RECORD><id>' + document.getElementById('requestid').value + "</id>";
	}
	else{
		params = 'command=new&id=' + count + '&xml=<RECORD><id>' + count + '</id>';
		count++;
	}
	var names = root.getElementsByTagName("name");
	var tags = root.getElementsByTagName("tag");	
	var elem;
	for(var x=0;x<names.length;x++){
		if(document.getElementById(names[x].childNodes[0].nodeValue.toLowerCase()+"1")){
			elem = document.getElementById(names[x].childNodes[0].nodeValue.toLowerCase()+"1");			
			paramname=names[x].childNodes[0].nodeValue.toLowerCase();
			params = params + "<" + paramname + ">";
			params = params + encodeURIComponent(elem.value) + "</"+ paramname +">" ;						
		}
		if(tags[x].childNodes[0].nodeValue === "radio_box"){
			var list = document.getElementsByName(names[x].childNodes[0].nodeValue.toLowerCase()+"1");
			for(var y=0;y<list.length;y++){
				if(list[y].checked){
					elem = list[y];
					break;
				}
			}
			paramname=names[x].childNodes[0].nodeValue.toLowerCase();
			params = params + "<" + paramname + ">";
			params = params + encodeURIComponent(elem.value) + "</"+ paramname +">" ;
		}
		
	}
	params = params+"</RECORD>"
	var callback = {
        success: modifySuccess,
        failure: requestFailed
    };
    YAHOO.util.Connect.asyncRequest('POST', 'modify', callback, params);
}


	/**
	*	Adds the newly-filled/edited record to database
	*/

function modifySuccess(){
	if(saveType == "edit")
		message("Record Updated");
	else
		message("Record Added");
}



/**
* Cookie Functions
*/
function setCookie(username, account){
    YAHOO.util.Cookie.set("user", username);  
	YAHOO.util.Cookie.set("acc", account);  	
}

function removeCookies(){
	YAHOO.util.Cookie.remove("user");
	YAHOO.util.Cookie.remove("acc");
}

/**
*	Log In
*/

function logIn(){

	var params = '';
	params="user="+document.getElementById('userinput').value+"&"+"pass="+document.getElementById('pass').value;
    var callback = {
        success: logInSuccess,
        failure: requestFailed
    };
	YAHOO.util.Connect.asyncRequest('POST', 'login', callback, params);
	message('Logging in ...');
	
		
}

/**
*	Log in Result
*/

function logInSuccess(request){
	var xml = request.responseXML;
    if (!xml) {
        error(request.responseText);
		alert("error");
        return
    }
	var root = xml.documentElement;
	if(root.nodeName == "error"){
		message(root.childNodes[0].nodeValue);
	}
	else{
		document.getElementById('userlogged').innerHTML = "Logged in as " + root.childNodes[0].childNodes[0].nodeValue +":";
		document.getElementById("changeuser").innerHTML = "Log out";
		setCookie(root.childNodes[0].childNodes[0].nodeValue, root.childNodes[1].childNodes[0].nodeValue);
		var tab2 = document.getElementById('recmanagement');
		if(root.childNodes[1].childNodes[0].nodeValue == "admin" || root.childNodes[1].childNodes[0].nodeValue == "member"){
			if (Dom.getStyle(tab2, 'display') == 'none') {
				Dom.setStyle(tab2, 'display', '');				//Record Management
				var linebreak2 = document.getElementById('linebreak2');
				linebreak2.innerHTML = '<hr/><br/>'
			}
		}
		message("Logged in as "+root.childNodes[0].childNodes[0].nodeValue);
		var login = document.getElementById('login');	
		Dom.setStyle(login, 'display', 'none');
		document.getElementById('userinput').value = "";
		document.getElementById('pass').value = "";
	}
}

/**
*	Log out
*/
function logOut(){
	if(YAHOO.util.Cookie.get("user")){
		removeCookies();
		document.getElementById('userlogged').innerHTML = "Logged in as guest:";
		document.getElementById("changeuser").innerHTML = "Log in";
		var tab2 = document.getElementById('recmanagement');
		Dom.setStyle(tab2, 'display', 'none');	
		var login = document.getElementById('login');	
		Dom.setStyle(login, 'display', 'none');
		document.getElementById('userinput').value = "";
		document.getElementById('pass').value = "";
		message("Logged out");
	}
	else{
		message("");
		var login = document.getElementById('login');	
		if (Dom.getStyle(login, 'display') == 'none') {
			Dom.setStyle(login, 'display', '');				
			var linebreak2 = document.getElementById('linebreak2');
			linebreak2.innerHTML = '<hr/><br/>'
		}
		else{
			Dom.setStyle(login, 'display', 'none');}	
	}
}

/**
*	Submit Record: toggles the choice for searching
*/
function submitRecord(){
	var bset = document.getElementById('buttonset2');	
    if (Dom.getStyle(bset, 'display') == 'none') {
        Dom.setStyle(bset, 'display', '');				
		var linebreak = document.getElementById('linebreak');
		linebreak.innerHTML = '<br/>'
    }
	else{
		Dom.setStyle(bset, 'display', 'none');
	}
	
}

/**
*	From Text: Displays a record form to be filled up and used as search keywords
*/
function getFromText(){
	var panel = document.getElementById('recordfortxt');	
    if (Dom.getStyle(panel, 'display') == 'none') {
        Dom.setStyle(panel, 'display', '');			
    }
}

/**
* Parser: Parses the strings from the text file and puts them in an array
*/

function parser(wholetext){
	var lines = new Array();
	newLines = new Array();
	var url = 'format/0';
	lines = wholetext.split(" $");	
	for(var i=0; i<lines.length; i++){
		newLines[i] = lines[i].slice(lines[i].indexOf('>') + 1, lines[i].length );		
	}
	var callback =
	{
	  success: assignToField,
	  failure: requestFailed
	};
	YAHOO.util.Connect.asyncRequest('GET', url, callback);
	
}

/**
*	Assign to Field: Assigns data to their respective text areas
*/

function assignToField(request){
	var xml = request.responseXML;
	if (!xml) {
        error(request.responseText);
		alert("error");
        return;
    }
	var root = xml.documentElement;
	var params = '';
	var names = root.getElementsByTagName("name");
	for(var x=2;x<names.length;x++){
		if(document.getElementById(names[x].childNodes[0].nodeValue.toLowerCase()+"2")){
			document.getElementById(names[x].childNodes[0].nodeValue.toLowerCase()+"2").value = newLines[x-2];
		}
		if(document.getElementById(newLines[x-2].toLowerCase()+"2")){
			document.getElementById(newLines[x-2].toLowerCase()+"2").click();
		}			
	}
}

/**
*	From File: Imports a record from file
*/
function getFromFile(){
	getFromText();	
	var allText = new Array();
	
	var handleSuccess = function(o){
		if(o.responseText !== undefined){
			allText = o.responseText;
			parser(allText);
		}
	}

	var handleFailure = function(o){
		if(o.responseText !== undefined){
			alert("fail!");
		}
	}

	var callback =
	{
	  success:handleSuccess,
	  failure: handleFailure
	};
	var request = YAHOO.util.Connect.asyncRequest('GET', document.getElementById('filename').value, callback);		
}


/**
*	Search: search for relevant records
*/

function search(){
	var url = 'format/0';
	var callback = {
		success: getParams,
		failure: requestFailed
	};
	YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

/**
*	Builds the parameters that will be sent to the controller for searching
*/
function getParams(request){
	var xml = request.responseXML;
	if (!xml) {
        error(request.responseText);
		alert("error");
        return;
    }
	var root = xml.documentElement;
	message("start");
	var params = "stricted=" +document.getElementById("strict").checked+"&ordered="+document.getElementById("ordered").checked+"&";
	var names = root.getElementsByTagName("name");
	var tags = root.getElementsByTagName("tag");
	var elem;
	for(var x=0;x<names.length;x++){
		if(document.getElementById(names[x].childNodes[0].nodeValue.toLowerCase()+"2")){
			elem = document.getElementById(names[x].childNodes[0].nodeValue.toLowerCase()+"2");
			params = params +""+names[x].childNodes[0].nodeValue.toLowerCase() +"="+encodeURIComponent(elem.value);
			if(names.length-1 != x)
			params = params +"&";
		}
		if(tags[x].childNodes[0].nodeValue === "radio_box"){
			var list = document.getElementsByName(names[x].childNodes[0].nodeValue.toLowerCase()+"2");
			for(var y=0;y<list.length;y++){
				if(list[y].checked){
					elem = list[y];
					break;
				}
			}
			params = params +""+names[x].childNodes[0].nodeValue.toLowerCase() +"="+encodeURIComponent(elem.value);
			if(names.length-1 != x)
			params = params +"&";
		}
		
	}
    var callback = {
        success: showQueryResponse,
        failure: requestFailed
    };
    YAHOO.util.Connect.asyncRequest('POST', 'search', callback, params);
	message('Query sent ...');
}

/**
*	Failed Access to the Server
*/
function requestFailed(request) {
	document.getElementById('query-result').innertHTML =
		"The request to the server failed.";
}

/**
*	If the search is a success, it shows how many results are retrieved, else displays an error message
*/
function showQueryResponse(request) {
    var xml = request.responseXML;
    if (!xml) {
        error(request.responseText);
		alert("error");
        return;
    }
	var root = xml.documentElement;
	if (root.nodeName == 'error') {
        var msg = '';
        var node = root.firstChild;
        while (node != null) {
            msg += node.nodeValue;
            node = node.nextSibling;
        }
        alert(msg);
	} else {
        var hits = root.getAttribute('hits');
        var elapsed = root.getAttribute('elapsed');
		document.getElementById('results').innerHTML =
			"Found " + hits + " records in " + elapsed + " seconds.";
		message('Retrieving results ...', false);
		retrieveNext();
	}
}

/**
*	Retrieves the format of the fields that will be displayed in the Result table
*/
function retrieveNext(){
	var url = 'format/1';
	var callback = {
		success: displayTable,
		failure: requestFailed
	};
	YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

/**
*	Displays the results in a table. It submits a GET action to the session to retrieve the results
*	It generates the table according to the format. Tables can be sorted by column, column movable
*	paginated and clickable.
*/
function displayTable(request) {
	var xml = request.responseXML;
	if (!xml) {
        error(request.responseText);
		alert("error");
        return;
    }
	var root = xml.documentElement;
	var names = root.getElementsByTagName("name");
	var types = root.getElementsByTagName("type");
	message('Results Retrieved..', false);		
	YAHOO.example.XHR_XML = new function() {
        
        var myColumnDefs = [
			{key:"RANK", resizeable:true,formatter:YAHOO.widget.DataTable.formatNumber, sortable:true},
        ];
		var data = [{key:"RANK", parser:"number"}];
		for(var x=0;x<names.length;x++){
			if(types[x].childNodes[0].nodeValue == "int"){
				myColumnDefs.push({key:names[x].childNodes[0].nodeValue, resizeable:true,formatter:YAHOO.widget.DataTable.formatNumber, sortable:true});
				data.push({key:names[x].childNodes[0].nodeValue, parser:"number"});
			}
			else{
				myColumnDefs.push({key:names[x].childNodes[0].nodeValue, resizeable:true, sortable:true});
				data.push(names[x].childNodes[0].nodeValue);
			}
		}
		myColumnDefs.push({key:"SCORE", resizeable:true, sortable:true});
		data.push("SCORE");
        this.myDataSource = new YAHOO.util.DataSource("results/0");
        this.myDataSource.connMethodPost = true;
        this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_XML;
        this.myDataSource.responseSchema = {
            resultNode: "RECORD",
            fields: data
        };
		
		var myConfigs = {
            sortedBy:{key:"RANK",dir:"asc"},
            paginator: new YAHOO.widget.Paginator({
                rowsPerPage: 25,
                template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
                rowsPerPageOptions: [10,25,50,100],
                pageLinks: 5
            }),
            draggableColumns:true,
			selectionMode:"single"
        }

        this.myDataTable = new YAHOO.widget.DataTable("tab4", myColumnDefs,this.myDataSource, myConfigs);	
		this.myDataTable.subscribe("rowMouseoverEvent", this.myDataTable.onEventHighlightRow);
        this.myDataTable.subscribe("rowMouseoutEvent", this.myDataTable.onEventUnhighlightRow);
		
       
		var onPrint = function(oArgs) {
			var elRow = oArgs.target;
			DoNav();
			this.unselectAllRows();
			this.selectRow(elRow);
			retrieveRecord(this.getRecord(elRow).getData("RANK"));
			};
		this.myDataTable.subscribe("rowClickEvent",onPrint);
		this.myDataTable.selectRow(this.myDataTable.getTrEl(0));
		
		
		
    };
	
}

/**
*	Retieves a single record according to the row clicked in the result table
*/
function retrieveRecord(num){
	var url = 'results/'+num;
	var callback = {
		success: recordRetrieved,
		failure: requestFailed
	};
	YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

/**
*	Displays the record in the left tab
*/
function recordRetrieved(request){
	document.getElementById('patientrecord').innerHTML = request.responseText;
}


/**
*	Function to display messages from the system
*/
function message(msg, timeout) {
    document.getElementById('messages').innerHTML = "<b>"+msg+"</b>";
    if (timeout)
        setTimeout(function() { document.getElementById('messages').innerHTML = ''; }, 3000);
}

function DoNav()
{  
	layout.getUnitByPosition('left').expand(); 
}
